package com.gongpingjialoan.activity.main;

import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.api.ApiSecurity;
import com.gongpingjialoan.bean.AuthBen;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.SmsContentObserver;
import com.gongpingjialoan.utility.MIUIUtils;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.Utils;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.xiaomi.account.openauth.XMAuthericationException;
import com.xiaomi.account.openauth.XiaomiOAuthConstants;
import com.xiaomi.account.openauth.XiaomiOAuthFuture;
import com.xiaomi.account.openauth.XiaomiOAuthResults;
import com.xiaomi.account.openauth.XiaomiOAuthorize;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @author huangcg
 * @Description 登录界面
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

    private TextView btn_login;

    // 手机号 ， 密码 文本输入框
    private EditText ed_phone, ed_verifycode, ed_psd;

    private UserManager mUserManager = null;

    private LoginActivity mySelf = this;
    ///
    private boolean isPhoneLegal, isCodeLegal, isPswLegal;

    private boolean isRefreshDiscountCar = true;

    private TextView mGetVerifycodeTv;

    private boolean isCountRunning = false;

    private View wxImageView, xmImageView;

    private XiaomiOAuthResults results;

    private View pwdView, verifycodeView, forgetView, registerView;

    private SmsContentObserver mSmsContentObserver;

    private RadioGroup mRadioGroup;

    private NetDataJson mNetDataJson;


    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "login";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("登录");
        EventBus.getDefault().register(this);
        isRefreshDiscountCar = getIntent().getBooleanExtra("isRefreshDiscountCar", true);
        btn_login = (TextView) findViewById(R.id.login);
        ed_phone = (EditText) findViewById(R.id.ed_phone);
        ed_psd = (EditText) findViewById(R.id.psd_edit);
        ed_verifycode = (EditText) findViewById(R.id.ed_verifycode);
        mGetVerifycodeTv = (TextView) findViewById(R.id.get_verifycode_tv);
//        mLoginSl = (ScrollView) findViewById(R.id.login_sl);
        pwdView = findViewById(R.id.pwd_rl);
        verifycodeView = findViewById(R.id.verifycode_rl);
        forgetView = findViewById(R.id.forget_psw);
        registerView = findViewById(R.id.register);
        wxImageView = findViewById(R.id.wx_id);
        xmImageView = findViewById(R.id.xm_id);
        mRadioGroup = (RadioGroup) findViewById(R.id.title_tab);
        mUserManager = new UserManager(this);
        btn_login.setOnClickListener(this);
        mGetVerifycodeTv.setOnClickListener(this);
        forgetView.setOnClickListener(this);
        registerView.setOnClickListener(this);
        xmImageView.setOnClickListener(this);
        wxImageView.setOnClickListener(this);
        if (!MIUIUtils.isMIUI()) {
            xmImageView.setVisibility(View.GONE);
            wxImageView.setPadding(0, 0, 0, 0);
        }
        initlistener();

        String phone = SharedPreferencesUtil.get(this, "loginPhone", "").toString();
        ed_phone.setText(phone);
        ed_phone.setSelection(phone.length());
        mSmsContentObserver = new SmsContentObserver(this, smsHandler);


        boolean show_back = getIntent().getBooleanExtra("show_back", true);
        findViewById(R.id.title_back).setVisibility(show_back ? View.VISIBLE : View.GONE);

    }


    private Handler smsHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (ed_verifycode != null) {
                    ed_verifycode.setText(msg.obj.toString());
                }
            }
        }
    };


    @Override
    public void onPause() {
        super.onPause();
        unRegisterSmsContentObservers();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerSmsContentObservers();
    }

    private void registerSmsContentObservers() {
        Uri smsUri = Uri.parse("content://sms");
        //smsContentObserver是SmsContentObserver的一个实例，可以在onCreate中初始化
        getContentResolver().registerContentObserver(smsUri, true, mSmsContentObserver);
    }

    private void unRegisterSmsContentObservers() {
        getContentResolver().unregisterContentObserver(mSmsContentObserver);
    }

    private void initlistener() {
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.psw_login) {
                    pwdView.setVisibility(View.VISIBLE);
                    verifycodeView.setVisibility(View.GONE);
                } else if (checkedId == R.id.verifycode_login) {
                    pwdView.setVisibility(View.GONE);
                    verifycodeView.setVisibility(View.VISIBLE);
                }
                getLoginLegal();
            }
        });

        ed_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if (ed_phone.getText().length() == 11) {
                    isPhoneLegal = true;
                    if (!isCountRunning) {
                        mGetVerifycodeTv.setEnabled(true);
                    }
                } else {
                    isPhoneLegal = false;
                    mGetVerifycodeTv.setEnabled(false);
                }
                getLoginLegal();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        ed_psd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (ed_psd.getText().length() > 0) {
                    isPswLegal = true;
                } else {
                    isPswLegal = false;
                }
                getLoginLegal();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        ed_verifycode.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if (ed_verifycode.getText().length() == 6) {
                    isCodeLegal = true;
                } else {
                    isCodeLegal = false;
                }
                getLoginLegal();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
    }


    private void getLoginLegal() {
        if (mRadioGroup.getCheckedRadioButtonId() == R.id.psw_login) {
            if (isPhoneLegal && isPswLegal) {
                btn_login.setEnabled(true);
            } else {
                btn_login.setEnabled(false);
            }
        } else {
            if (isPhoneLegal && isCodeLegal) {
                btn_login.setEnabled(true);
            } else {
                btn_login.setEnabled(false);
            }
        }

    }


    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.login:
                SharedPreferencesUtil.put(this, "loginPhone", ed_phone.getText().toString());
                if (mRadioGroup.getCheckedRadioButtonId() == R.id.psw_login) {
                    loginWithPsw();
                } else {
                    loginWithVergifyCode();
                }
                break;
            case R.id.get_verifycode_tv:
                getVergifyCode();
                break;
            case R.id.forget_psw:
                StepMonitor.getInstance().addMonitor(new Monitor("click", "my_modifyPassword", System.currentTimeMillis(), 1.0f));
                startActivity(new Intent(this, ForgetPswActivity.class));
                break;
            case R.id.register:
                startActivityForResult(new Intent(this, RegisterActivity.class), 11);
                break;
            case R.id.wx_id:
                sendWxAuthRequest();
                break;
            case R.id.xm_id:
                showProgressDialog("登录中...");
                getMiCode();
                break;
            default:
                break;
        }
    }


    /**
     * 微信登录
     */
    private void sendWxAuthRequest() {
        if (GPJApplication.getInstance().wxApi.isWXAppInstalled()) {
            showProgressDialog("登录中...");
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "gongpingjia_login";
            //拉起微信授权，授权结果在WXEntryActivity中接收处理
            GPJApplication.getInstance().wxApi.sendReq(req);
        } else {
            Toast.makeText(this, "请安装微信", Toast.LENGTH_SHORT).show();
        }
    }

    private void loginWithPsw() {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "login_password", System.currentTimeMillis(), 1.0f));
        String phone_num = ed_phone.getText().toString();
        String psw = ed_psd.getText().toString();
        Utils.autoCloseKeyboard(LoginActivity.this, btn_login);
        showProgressDialog("登录中...");
        mUserManager.login(phone_num, psw, isRefreshDiscountCar, new UserManager.OnLoginResponse() {
            @Override
            public void onLoginSuccess(UserManager user) {
                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                hidenProgressDialog();
                Intent intent = getIntent();
                intent.putExtra("phone", user.getPhone());
                setResult(RESULT_OK, intent);
                mySelf.finish();
            }

            @Override
            public void onLoginError(String errorMessage) {
                hidenProgressDialog();
                Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void loginWithVergifyCode() {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "login_captcha", System.currentTimeMillis(), 1.0f));
        String phone_num = ed_phone.getText().toString();
        String captcha = ed_verifycode.getText().toString();
        Utils.autoCloseKeyboard(LoginActivity.this, btn_login);
        showProgressDialog("登录中...");
        mUserManager.loginWithVerifyCode(phone_num, captcha, isRefreshDiscountCar, new UserManager.OnLoginResponse() {

            @Override
            public void onLoginError(String msg) {
                hidenProgressDialog();
                Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLoginSuccess(UserManager user) {
                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                hidenProgressDialog();
                Intent intent = getIntent();
                intent.putExtra("phone", user.getPhone());
                setResult(RESULT_OK, intent);
                mySelf.finish();
            }
        }, "");
    }


    private void getVergifyCode() {
        mGetVerifycodeTv.setEnabled(false);
        isCountRunning = true;
        new CountDownTimer(Const.CODE_TIME * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mGetVerifycodeTv.setText(millisUntilFinished / 1000 + "秒");

            }

            @Override
            public void onFinish() {
                isCountRunning = false;
                if (ed_phone.getText().length() == 11) {
                    mGetVerifycodeTv.setEnabled(true);
                }
                mGetVerifycodeTv.setText("重新发送");
            }
        }.start();
        mNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                Toast.makeText(LoginActivity.this, " 我们将给您来电告知验证码，请注意接听", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
        String url = "/mobile/api/get-captcha/";
        mNetDataJson.addParam("phone", ed_phone.getText().toString());
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.addParam("sign", ApiSecurity.security(GPJApplication.getInstance().getSecert(),ed_phone.getText().toString()));
        mNetDataJson.setUrl(url);
        mNetDataJson.request("post");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 11) {
            Intent it = getIntent();
            setResult(RESULT_OK,it);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        if (o instanceof AuthBen) {
            AuthBen authBen = (AuthBen) o;
            if (TextUtils.isEmpty(authBen.code)) {
                hidenProgressDialog();
                return;
            }
            mUserManager.loginfromSF(authBen.code, new UserManager.OnSfLoninResponse() {
                @Override
                public void onLoginSuccess() {
                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                    hidenProgressDialog();
                    Intent it = getIntent();
                    setResult(RESULT_OK,it);
                    mySelf.finish();
                }

                @Override
                public void onLoginBindPhone() {
                    hidenProgressDialog();
                    Intent intent = new Intent(mySelf, BindPhoneActivity.class);
                    intent.putExtra("isRefreshDiscountCar", isRefreshDiscountCar);
                    intent.putExtra("login_type", "weixin");
                    startActivityForResult(intent, 11);
                }

                @Override
                public void onLoginError(String errorMessage) {
                    hidenProgressDialog();
                    Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
                }
            }, isRefreshDiscountCar, "/mobile/account/wechat-login/");
        }
    }


    private void getMiCode() {
        XiaomiOAuthFuture<XiaomiOAuthResults> future = new XiaomiOAuthorize()
                .setAppId(Const.XM_APP_ID)
                .setRedirectUrl(Const.XM_APP_RETURN_URL)
                .setScope(new int[]{XiaomiOAuthConstants.SCOPE_PROFILE, XiaomiOAuthConstants.SCOPE_OPEN_ID})
                .startGetOAuthCode(this);
        waitAndShowFutureResult(future);
    }

    private <V> void waitAndShowFutureResult(final XiaomiOAuthFuture<V> future) {
        new AsyncTask<Void, Void, V>() {
            Exception e;

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected V doInBackground(Void... params) {
                V v = null;
                try {
                    v = future.getResult();
                } catch (IOException e1) {
                    this.e = e1;
                } catch (OperationCanceledException e1) {
                    this.e = e1;
                } catch (XMAuthericationException e1) {
                    this.e = e1;
                }
                return v;
            }

            @Override
            protected void onPostExecute(V v) {
                if (v != null) {
                    if (v instanceof XiaomiOAuthResults) {
                        results = (XiaomiOAuthResults) v;
                    }
                    if (results.hasError()) {
                        hidenProgressDialog();
                        Toast.makeText(mySelf, "授权出错,请检测您的小米帐号是否登录", Toast.LENGTH_SHORT).show();
                    } else {
                        mUserManager.loginfromSF(results.getCode(), new UserManager.OnSfLoninResponse() {
                            @Override
                            public void onLoginSuccess() {
                                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                                hidenProgressDialog();
                                Intent it = getIntent();
                                setResult(RESULT_OK,it);
                                mySelf.finish();
                            }

                            @Override
                            public void onLoginBindPhone() {
                                hidenProgressDialog();
                                Intent intent = new Intent(mySelf, BindPhoneActivity.class);
                                intent.putExtra("isRefreshDiscountCar", isRefreshDiscountCar);
                                intent.putExtra("login_type", "xiaomi");
                                startActivityForResult(intent, 11);
                            }

                            @Override
                            public void onLoginError(String errorMessage) {
                                hidenProgressDialog();
                                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
                            }
                        }, isRefreshDiscountCar, "/mobile/account/xiaomi-login/");
                    }


                } else if (e != null) {
                    hidenProgressDialog();
                    if (e instanceof OperationCanceledException) {
                        Toast.makeText(mySelf, "授权取消!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(mySelf, "授权出错,请检测您的小米帐号是否登录", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    hidenProgressDialog();
                    Toast.makeText(mySelf, "授权出错！", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!getIntent().getBooleanExtra("show_back", true)) {
                return false;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
